package com.ubing.boot.notesforjava.test.file;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class HelloClient {

    public static void main(String[] args) throws InterruptedException {
        // 1. 启动类
        new Bootstrap()
                // 2.添加 EventLoop
                .group(new NioEventLoopGroup())
                // 3.选择客户端channel 实现
                .channel(NioSocketChannel.class)
                // 4.添加处理器handler
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override // 在连接建立后被调用
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                // main 异步链接
                .connect(new InetSocketAddress("127.0.0.1", 8080))
                .sync()// 阻塞等待连接成功
                .channel() // 代表连接对象
                //向服务器发送数据
                .writeAndFlush("Hello Netty");
    }
}
